import json
from pathlib import Path
from library_system.models import Book


class DataManager:
    def __init__(self, file_name="books.json"):
        # 向上三级目录定位到项目根目录，再进入ressources
        self.file_path = Path(__file__).resolve().parent.parent.parent / 'ressources' / file_name
        print(f"Debug: New file path is {self.file_path}")

    def load_books(self):
        try:
            with open(self.file_path, "r", encoding="utf-8") as file:
                data = json.load(file)
            return [Book(**book) for book in data["books"]]
        except Exception as e:
            print(f"Error loading books: {e}")
        return []

    def save_books(self, books):
        try:
            data = {"books": [vars(book) for book in books]}
            with open(self.file_path, "w", encoding="utf-8") as file:
                json.dump(data, file, ensure_ascii=False, indent=2)
            print("Debug: Books saved successfully.")
        except Exception as e:
            print(f"Error saving books: {e}")